package logic

import (
	"context"
	"fmt"
	"strconv"

	"probe-users/internal/errorx"
	"probe-users/internal/svc"
	"probe-users/internal/utils"
	"probe-users/pb/users"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserRolesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserRolesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserRolesLogic {
	return &GetUserRolesLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserRolesLogic) GetUserRoles(in *users.GetUserRolesRequest) (*users.GetUserRolesResponse, error) {
	// 参数验证
	if err := l.validate(in); err != nil {
		return nil, err
	}

	// 解析Token
	claims, err := utils.ParseToken(in.Token, l.svcCtx.Config.JWTAuth.AccessSecret)
	if err != nil {
		return nil, err
	}

	// 确定查询的用户ID（默认查当前用户）
	targetUserID := in.UserId
	if targetUserID == 0 {
		targetUserID = claims.UserId
	}

	// 检查权限：管理员可以查询其他用户的角色，普通用户只能查询自己的
	if targetUserID != claims.UserId {
		hasPermission, err := l.svcCtx.Enforcer.Enforce(strconv.FormatInt(claims.RoleId, 10), "user", "query_roles:other")
		if err != nil {
			return nil, errors.Wrapf(err, "检查权限失败")
		}
		if !hasPermission {
			return nil, errorx.ErrPermissionDenied
		}
	}

	// 检查用户是否存在
	_, err = l.svcCtx.UserModel.FindOne(targetUserID)
	if err != nil {
		return nil, errors.Wrapf(err, "查询用户失败: %d", targetUserID)
	}

	// 查询用户的所有角色（RBAC模型中用户可能有多个角色）
	userIDStr := fmt.Sprintf("%d", targetUserID)
	roleIDStrs, err := l.svcCtx.Enforcer.GetRolesForUser(userIDStr)
	if err != nil {
		return nil, errors.Wrapf(err, "查询用户角色失败: %d", targetUserID)
	}

	// 转换角色ID字符串为int64，并查询角色名称
	roleIDs := make([]int64, 0, len(roleIDStrs))
	roleNames := make([]string, 0, len(roleIDStrs))
	for _, roleIDStr := range roleIDStrs {
		roleID, err := utils.StringToInt64(roleIDStr)
		if err != nil {
			continue // 忽略无效的角色ID
		}
		roleIDs = append(roleIDs, roleID)

		// 查询角色名称
		role, err := l.svcCtx.RoleModel.FindOne(roleID)
		if err == nil && role != nil {
			roleNames = append(roleNames, role.Name)
		} else {
			roleNames = append(roleNames, fmt.Sprintf("unknown(%d)", roleID))
		}
	}

	return &users.GetUserRolesResponse{
		RoleIds:   roleIDs,
		RoleNames: roleNames,
	}, nil
}

func (l *GetUserRolesLogic) validate(in *users.GetUserRolesRequest) error {
	if in.Token == "" {
		return errorx.ErrTokenNotEmpty
	}
	return nil
}
